<template>
  <view class="product-list">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <input 
          class="search-input" 
          placeholder="搜索商品" 
          v-model="searchKeyword"
          @confirm="handleSearch"
        />
        <text class="search-icon">🔍</text>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view class="filter-item" @click="showSortPopup = true">
        <text>{{ sortText }}</text>
        <text class="arrow">▼</text>
      </view>
      <view class="filter-item" @click="showCategoryPopup = true">
        <text>{{ categoryText }}</text>
        <text class="arrow">▼</text>
      </view>
      <view class="filter-item" @click="showPricePopup = true">
        <text>{{ priceText }}</text>
        <text class="arrow">▼</text>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="product-grid">
      <view 
        class="product-item" 
        v-for="product in productList" 
        :key="product.id"
        @click="goToDetail(product.id)"
      >
        <image class="product-image" :src="product.mainImage" mode="aspectFill" />
        <view class="product-info">
          <text class="product-title">{{ product.name }}</text>
          <text class="product-price">¥{{ product.price }}</text>
          <text class="product-sales">已售{{ product.sales || 0 }}</text>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && !loadingMore">
      <text @click="loadMore">加载更多</text>
    </view>

    <!-- 加载中提示 -->
    <view class="loading" v-if="loadingMore">
      <text>加载中...</text>
    </view>

    <!-- 没有更多数据提示 -->
    <view class="no-more" v-if="!hasMore && productList.length > 0">
      <text>没有更多数据了</text>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="productList.length === 0 && !loading">
      <image src="/static/images/empty.png" mode="aspectFit" class="empty-image" />
      <text class="empty-text">暂无商品</text>
    </view>

    <!-- 排序弹窗 -->
    <view class="popup-mask" v-if="showSortPopup" @click="showSortPopup = false">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">排序方式</text>
          <text class="popup-close" @click="showSortPopup = false">✕</text>
        </view>
        <view class="popup-body">
          <view 
            class="popup-item" 
            v-for="item in sortOptions" 
            :key="item.value"
            @click="selectSort(item.value)"
          >
            <text>{{ item.label }}</text>
            <text v-if="currentSort === item.value" class="selected-icon">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 分类弹窗 -->
    <view class="popup-mask" v-if="showCategoryPopup" @click="showCategoryPopup = false">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择分类</text>
          <text class="popup-close" @click="showCategoryPopup = false">✕</text>
        </view>
        <view class="popup-body">
          <view 
            class="popup-item" 
            @click="selectCategory(null)"
          >
            <text>全部分类</text>
            <text v-if="currentCategory === null" class="selected-icon">✓</text>
          </view>
          <view 
            class="popup-item" 
            v-for="category in categoryList" 
            :key="category.id"
            @click="selectCategory(category.id)"
          >
            <text>{{ category.name }}</text>
            <text v-if="currentCategory === parseInt(category.id)" class="selected-icon">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 价格弹窗 -->
    <view class="popup-mask" v-if="showPricePopup" @click="showPricePopup = false">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">价格区间</text>
          <text class="popup-close" @click="showPricePopup = false">✕</text>
        </view>
        <view class="popup-body">
          <view class="price-inputs">
            <input 
              class="price-input" 
              placeholder="最低价" 
              v-model="minPrice"
              type="number"
            />
            <text class="price-separator">-</text>
            <input 
              class="price-input" 
              placeholder="最高价" 
              v-model="maxPrice"
              type="number"
            />
          </view>
          <view class="price-buttons">
            <button class="price-btn reset" @click="resetPrice">重置</button>
            <button class="price-btn confirm" @click="confirmPrice">确定</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
import { productApi, categoryApi } from '@/api/index.js';
import common from '@/utils/common.js';

// 响应式数据
const loading = ref(false);
const productList = ref([]);
const categoryList = ref([]);
const hasMore = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const loadingMore = ref(false); // 新增：加载更多状态标识

// 搜索和筛选
const searchKeyword = ref('');
const currentSort = ref('default');
const currentCategory = ref(null);
const minPrice = ref('');
const maxPrice = ref('');

// 弹窗控制
const showSortPopup = ref(false);
const showCategoryPopup = ref(false);
const showPricePopup = ref(false);

// 排序选项
const sortOptions = [
  { label: '默认排序', value: 'default' },
  { label: '价格从低到高', value: 'price_asc' },
  { label: '价格从高到低', value: 'price_desc' },
  { label: '销量从高到低', value: 'sales_desc' },
  { label: '最新上架', value: 'newest' }
];

// 计算属性
const sortText = computed(() => {
  const option = sortOptions.find(item => item.value === currentSort.value);
  return option ? option.label : '排序';
});

const categoryText = computed(() => {
  if (currentCategory.value === null) return '全部分类';
  const category = categoryList.value.find(item => item.id === currentCategory.value);
  return category ? category.name : '选择分类';
});

const priceText = computed(() => {
  if (minPrice.value && maxPrice.value) {
    return `¥${minPrice.value}-¥${maxPrice.value}`;
  } else if (minPrice.value) {
    return `¥${minPrice.value}以上`;
  } else if (maxPrice.value) {
    return `¥${maxPrice.value}以下`;
  }
  return '价格区间';
});

// 加载商品列表
const loadProducts = async (reset = false) => {
  if (loading.value) return Promise.resolve();
  
  if (reset) {
    loading.value = true;
    currentPage.value = 1;
    productList.value = [];
  } else {
    loadingMore.value = true;
  }

  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    keyword: searchKeyword.value
  };
  
  // 只有当categoryId不为null时才添加到参数中
  if (currentCategory.value !== null) {
    params.categoryId = currentCategory.value;
  }

  // 添加价格区间参数
  if (minPrice.value) {
    params.minPrice = minPrice.value;
  }
  if (maxPrice.value) {
    params.maxPrice = maxPrice.value;
  }

  // 添加排序参数
  if (currentSort.value === 'price_asc') {
    params.sortBy = 'price';
    params.sortOrder = 'asc';
  } else if (currentSort.value === 'price_desc') {
    params.sortBy = 'price';
    params.sortOrder = 'desc';
  } else if (currentSort.value === 'sales_desc') {
    params.sortBy = 'sales';
    params.sortOrder = 'desc';
  } else if (currentSort.value === 'newest') {
    params.sortBy = 'createTime';
    params.sortOrder = 'desc';
  }

  try {
    console.log(`加载商品列表: 第${currentPage.value}页, 每页${pageSize.value}条`);
    const res = await productApi.getProductList(params);
    
    if (res.code === 200) {
      const newProducts = res.data.items || res.data || [];
      if (reset) {
        productList.value = newProducts;
      } else {
        productList.value.push(...newProducts);
      }
      
      hasMore.value = newProducts.length === pageSize.value;
      console.log(`加载了${newProducts.length}条商品数据, 是否有更多: ${hasMore.value}`);
    }
    return Promise.resolve();
  } catch (error) {
    console.error('加载商品列表失败:', error);
    common.showError('加载失败');
    return Promise.reject(error);
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await categoryApi.getCategories();
    if (res.code === 200) {
      categoryList.value = res.data || [];
    }
    return Promise.resolve();
  } catch (error) {
    console.error('加载分类失败:', error);
    return Promise.reject(error);
  }
};

// 搜索处理
const handleSearch = () => {
  loadProducts(true);
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    currentPage.value++;
    loadProducts();
  }
};

// 选择排序
const selectSort = (sort) => {
  currentSort.value = sort;
  showSortPopup.value = false;
  loadProducts(true);
};

// 选择分类
const selectCategory = (categoryId) => {
  currentCategory.value = categoryId === null ? null : parseInt(categoryId);
  showCategoryPopup.value = false;
  loadProducts(true);
};

// 确认价格筛选
const confirmPrice = () => {
  showPricePopup.value = false;
  loadProducts(true);
};

// 重置价格筛选
const resetPrice = () => {
  minPrice.value = '';
  maxPrice.value = '';
};

// 跳转到商品详情
const goToDetail = (productId) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${productId}`
  });
};

// 生命周期
onLoad((options) => {
  // 处理从其他页面传递过来的参数
  if (options.categoryId) {
    // 将字符串转换为数字类型，确保类型匹配
    currentCategory.value = parseInt(options.categoryId);
  }
  if (options.keyword) {
    searchKeyword.value = options.keyword;
  }
  
  // 先加载分类数据，然后再加载商品数据，确保分类数据已加载
  loadCategories().then(() => {
    loadProducts(true);
  });
});

onMounted(() => {
  // 如果没有通过 onLoad 获取参数，则在 onMounted 中加载数据
  if (!currentCategory.value && !searchKeyword.value) {
    loadProducts(true);
    loadCategories();
  }
});

// 下拉刷新处理
onPullDownRefresh(() => {
  console.log("商品列表页面下拉刷新触发");
  // 重置页码并重新加载数据
  currentPage.value = 1;
  
  // 先加载分类数据，然后再加载商品数据
  loadCategories().then(() => {
    loadProducts(true).then(() => {
      console.log("刷新完成，停止下拉刷新动画");
      uni.stopPullDownRefresh();
    });
  });
});

// 滚动到底部加载更多
onReachBottom(() => {
  console.log("商品列表页面滚动到底部触发");
  if (hasMore.value && !loading.value) {
    currentPage.value++;
    loadProducts();
  }
});
</script>

<style scoped>
.product-list {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 搜索栏 */
.search-bar {
  padding: 20rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  flex: 1;
  height: 70rpx;
  padding: 0 80rpx 0 20rpx;
  background: #f5f5f5;
  border-radius: 35rpx;
  font-size: 28rpx;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  font-size: 32rpx;
  color: #999;
}

/* 筛选栏 */
.filter-bar {
  display: flex;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.filter-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  font-size: 28rpx;
  color: #333;
}

.arrow {
  margin-left: 10rpx;
  font-size: 24rpx;
  color: #999;
}

/* 商品网格 */
.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  padding: 20rpx;
}

.product-item {
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 300rpx;
}

.product-info {
  padding: 20rpx;
}

.product-title {
  display: block;
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  display: block;
  font-size: 32rpx;
  color: #ff4757;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.product-sales {
  display: block;
  font-size: 24rpx;
  color: #999;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 40rpx;
  color: #666;
  font-size: 28rpx;
}

/* 加载中提示 */
.loading {
  text-align: center;
  padding: 40rpx;
  color: #666;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading::before {
  content: "";
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
  border: 4rpx solid #f5f5f5;
  border-top: 4rpx solid #ff4757;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 没有更多数据提示 */
.no-more {
  text-align: center;
  padding: 40rpx;
  color: #666;
  font-size: 28rpx;
  position: relative;
}

.no-more::before,
.no-more::after {
  content: "";
  display: inline-block;
  width: 100rpx;
  height: 2rpx;
  background: #ddd;
  vertical-align: middle;
  margin: 0 20rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 弹窗样式 */
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

.popup-content {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 60vh;
  width: 100%;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 32rpx;
  color: #999;
}

.popup-body {
  padding: 20rpx 0;
}

.popup-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #f5f5f5;
}

.selected-icon {
  color: #007aff;
  font-weight: bold;
}

/* 价格输入 */
.price-inputs {
  display: flex;
  align-items: center;
  padding: 30rpx;
  gap: 20rpx;
}

.price-input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.price-separator {
  font-size: 28rpx;
  color: #999;
}

.price-buttons {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
}

.price-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.price-btn.reset {
  background: #f5f5f5;
  color: #666;
}

.price-btn.confirm {
  background: #007aff;
  color: #fff;
}
</style> 